package com.ydgk.dao;

import com.ydgk.bean.Admin;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.List;

public class AdminDao extends BaseDao<Admin>{
    @Override
    public int save(Admin admin) {
        return template.update("insert into admin values(?,?,?,?,?,?,?,?)",
                admin.getAid(),
                admin.getAname(),
                admin.getApass(),
                admin.getAsex(),
                admin.getAphone(),
                admin.getAemail(),
                admin.getBirthday(),
                admin.getAphoto());
    }

    @Override
    public int updateById(Admin admin) {
        return template.update("update admin set aname = ?,apass = ?,asex = ?,aphone = ?,aemail = ?,birthday = ?,aphoto = ? where aid = ?",
                admin.getAname(),
                admin.getApass(),
                admin.getAsex(),
                admin.getAphone(),
                admin.getAemail(),
                admin.getBirthday(),
                admin.getAphoto(),
                admin.getAid());
    }

    @Override
    public int deleteById(int id) {
        try {
            return template.update("delete from admin where aid = ?", id);
        }catch (Exception e){
            return -1;
        }
    }

    @Override
    public List<Admin> findAll() {
        return null;
    }

    @Override
    public Admin findById(int id) {
        String sql = "select * from admin where aid =?" ;
        List<Admin> list = template.query(sql, new BeanPropertyRowMapper<Admin>(Admin.class),id);
        return list.size() > 0 ? list.get(0) : null ;
    }

    @Override
    public List<Admin> paging(int pageNumber) {
        return template.query("select * from admin order by aid desc limit ?,?",new BeanPropertyRowMapper<Admin>(Admin.class) , (pageNumber-1)*pageCount ,pageCount);
    }

    public Admin login(Admin admin){
        try{
            return template.queryForObject("select *from admin where aname = ? and apass = ?",new BeanPropertyRowMapper<Admin>(Admin.class),admin.getAname(),admin.getApass());
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }
}
